package com.my.xq.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.my.wechat.domain.vo.WeChatMediaVO;
import com.my.xq.domain.ProprietorIntroParam;
import com.my.xq.domain.ProprietorQueryParam;
import com.my.xq.domain.ProprietorRegisterParam;
import com.my.xq.domain.entity.Proprietor;
import com.my.xq.repository.DoorplateRepository;
import com.my.xq.repository.ProprietorRepository;
import com.sskj.core.annotation.ControllerLogExeTime;
import com.sskj.sys.domain.entity.MediaEntity;
import com.sskj.sys.repository.MediaRepository;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

@RestController
@RequestMapping("/yz")
public class ProprietorServiceImpl {
	@Autowired
	ProprietorRepository proprietorRepository;

	@Autowired
	DoorplateRepository doorplateRepository;

	@Autowired
	MediaRepository mediaRepository;

	@Autowired
	FileUploadMediaServiceImpl fileUpload;

	@Value("${sskj.conf.fileUploadPath}")
	private String mediaUploadPath;

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/phone", method = { RequestMethod.GET })
	@ControllerLogExeTime(description = "根据身份证号码查询业主手机号码")
	public String getPhoneByCertNum(String certNum) {
		logger.debug(certNum);
		String phone = proprietorRepository.getPhoneByCertNum(certNum);
		logger.debug(phone);
		return phone;
	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/updIntro", method = { RequestMethod.POST })
	@ApiOperation(value = "更新业主信息", notes = "更新个人简介信息（学历，简介，照片）", httpMethod = "POST")
	public boolean updIntro(ProprietorIntroParam param, HttpServletRequest request) {
		logger.debug("个人简介信息更新开始");
		logger.debug(JSON.toJSONString(param));

		try {
			MediaEntity me = new MediaEntity();
			// 1、上传照片
			if (param.getMedataBase64() != null) {

				WeChatMediaVO image = new WeChatMediaVO();
				image.setFileName(param.getFileName());
				image.setMedataBase64(param.getMedataBase64());
				image.setMediaSuffix(param.getMediaSuffix());
				image.setMediaId(param.getMediaId());
				image.setMediaType(param.getMediaType());
				me = fileUpload.uploadImg(image, request);
			} else {
				me.setHttpurl(null);
			}
			// 2、保存个人信息到数据库
			proprietorRepository.updIntro(param.getProprietorId(), param.getRecord(), param.getSynopsis(), me.getHttpurl());
		} catch (Exception e) {
			return false;
		}

		logger.debug("个人简介信息更新结束");
		return true;
	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/register", method = { RequestMethod.POST })
	@ApiOperation(value = "微信用户绑定", notes = "将微信用户同业主信息进行关联", httpMethod = "POST")
	public boolean register(ProprietorRegisterParam param) {
		logger.debug("参数: [{}]", JSON.toJSON(param));
		Proprietor p = proprietorRepository.findPropriByCard(param.getCertNum());
		if (p == null) {
			return false;
		} else {
			p.setOpenid(param.getOpenId());
			try {
				proprietorRepository.save(p);
				doorplateRepository.updateOpenIdByProprietorId(param.getOpenId(), p.getId());
				logger.debug("绑定成功");
				return true;
			} catch (Exception e) {
				return false;
			}
		}
	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/addyzInfo", method = { RequestMethod.POST })
	@ControllerLogExeTime(description = "添加业主信息")
	public void addyzInfo(Proprietor p) {
		if (null != p.getId() && !"".equals(p.getId())) {
			Proprietor ps = proprietorRepository.get(p.getId());
			p.setPriType(ps.getPriType());
			p.setProprietorId(ps.getProprietorId());
		}
		proprietorRepository.save(p);
		if (!p.getFiles().isEmpty()) {
			mediaRepository.updateMedia(p.getId(), this.toList(p.getFiles(), ","));
		}

		mediaRepository.delMedia(p.getId(), this.toList(p.getFiles().isEmpty() ? "XXXXX" : p.getFiles(), ","));
	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/findAll", method = { RequestMethod.GET })
	@ControllerLogExeTime(description = "查询业主信息")
	@ApiOperation(value = "查询业主信息", httpMethod = "GET")
	@ApiImplicitParams({ @ApiImplicitParam(name = "name", value = "姓名", paramType = "form", dataType = "string"),
			@ApiImplicitParam(name = "pageNumber", value = "页号", paramType = "form", dataType = "int"),
			@ApiImplicitParam(name = "pageSize", value = "页的大小", paramType = "form", dataType = "int") })
	public Page<Proprietor> findAllPage(@ApiIgnore ProprietorQueryParam pqp, @ApiIgnore Pageable pageable,
			HttpServletRequest request) {
		Page<Proprietor> page = proprietorRepository.findPage(pqp, pageable);
		return page;
	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@ControllerLogExeTime(description = "查询一条业主记录", log = false)
	@RequestMapping("/findOne")
	public Proprietor findOne(String id, HttpServletRequest request) {
		Proprietor court = proprietorRepository.get(id);
		return court;
	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@ControllerLogExeTime(description = "删除业主信息", log = false)
	@RequestMapping("/delyzInfo")
	public void delyz(String id) {
		proprietorRepository.delete(id);
		doorplateRepository.unbindProprietor(id);
		mediaRepository.delMedia(id, this.toList("XXXXX", ","));
	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/checkCert")
	@ApiOperation(value = "身份证号码获取业主信息记录", notes = "身份证号码获取业主信息记录", httpMethod = "GET")
	@ApiImplicitParams({ @ApiImplicitParam(name = "cert", value = "cert", paramType = "form", dataType = "string") })
	public Proprietor checkCert(@ApiIgnore ProprietorQueryParam p) {

		System.out.println("p code=" + p.getCard());
		Proprietor pEntity = proprietorRepository.findByCert(p.getCard());
		if (pEntity != null) {
			return pEntity;
		}
		return null;
	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/checkCard")
	@ApiOperation(value = "身份证号码获取业主信息记录", notes = "身份证号码获取业主信息记录", httpMethod = "GET")
	@ApiImplicitParams({ @ApiImplicitParam(name = "cert", value = "cert", paramType = "form", dataType = "string") })
	public Proprietor checkCard(@ApiIgnore ProprietorQueryParam p) {
		System.out.println("p code=" + p.getCard());
		return proprietorRepository.findPropriByCard(p.getCard());
	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@ControllerLogExeTime(description = "通过openId获取用户信息", log = false)
	@RequestMapping(value = "/getProprietorById", method = { RequestMethod.GET })
	public Proprietor getProprietorById(String id) {
		Proprietor result = proprietorRepository.get(id);
		if (result == null) {
			return new Proprietor();
		}
		return result;
	}

	public List<String> toList(String value, String separator) {
		List<String> result = new ArrayList<String>();
		if (!this.isEmpty(value)) {
			String[] as = value.split(separator);
			for (int i = 0; i < as.length; i++) {
				result.add(as[i]);
			}
		}
		return result;
	}

	public boolean isEmpty(String str) {
		return str == null || str.length() == 0;
	}
}
